from copy import deepcopy
import json
import logging
import os
from typing import Any, Dict

from sqlmodel import SQLModel, Session

from db import new_session
from db.model.llm import LLM, LLMFactory
from utils.file_utils import get_project_base_directory

def save_model(model: SQLModel, data: Dict[str, Any], session: Session):
    db_model = model(**data)
    session.merge(db_model)

def init_llm_factory():
    try:
        with open(os.path.join(get_project_base_directory(), "conf", "llm_factories.json"), "r") as f:
            factory_llm_infos = json.load(f)["factory_llm_infos"]
    except Exception:
        logging.warning("load llm_factories.json failed")
        factory_llm_infos = []
    
    with new_session() as session:
        for factory_llm_info in factory_llm_infos:
            info = deepcopy(factory_llm_info)
            llm_infos = info.pop("llm")
            try:
                save_model(LLMFactory, info, session)
            except Exception as e:
                logging.error(f"init_llm_factory save_model LLMFactory error: {str(e)}", exc_info=True)
                pass
            for llm_info in llm_infos:
                llm_info["fid"] = factory_llm_info["name"]
                try:
                    save_model(LLM, llm_info, session)
                except Exception as e:
                    logging.error(f"init_llm_factory save_model LLM error: {str(e)}", exc_info=True)
                    pass
                
        session.commit()